import requests
import json


def call_toutiao_api():
    """
    调用头条新闻API接口
    """
    url = "http://v.juhe.cn/toutiao/index"
    params = {
        "key": "38f988eb528aef4e5fa0c5cae4061b1f",
        "type": "keji"
    }

    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()  # 检查HTTP状态码
        return response.text
    except requests.exceptions.RequestException as e:
        print(f"API请求失败: {str(e)}")
        return None


def parse_api_result(json_str):
    """
    解析API返回的JSON数据
    """
    try:
        result = json.loads(json_str)
        if result.get("reason") == "success":
            return result["result"]
        else:
            print(f"API返回错误: {result.get('reason')}")
            return None
    except json.JSONDecodeError:
        print("JSON解析失败")
        return None


# 使用示例
if __name__ == "__main__":
    # 调用API
    api_response = call_toutiao_api()

    if api_response:
        # 解析结果
        parsed_data = parse_api_result(api_response)

        if parsed_data:
            print("成功获取数据：")
            print(f"当前页码: {parsed_data['page']}")
            print(f"每页数量: {parsed_data['pageSize']}")
            print("\n新闻列表：")
            for news in parsed_data["data"]:
                print(f"标题: {news['title']}")
                print(f"发布时间: {news['date']}")
                print(f"来源: {news['author_name']}")
                print("--------------------")
